package com.atguigu.springcloud.subscrib;

import com.alibaba.fastjson.JSON;
import com.atguigu.springcloud.event.InnerProtocolMessageEvent;
import com.atguigu.springcloud.event.NormalProtocolMessageEvent;
import com.atguigu.springcloud.message.InnerProtocol;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.context.ApplicationContext;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;

import java.util.Map;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 运用springcloudstream消息驱动监听消息
 * @date 2021/10/11 16:39
 */
@Slf4j
public class DefaultMessageListener {


    @Autowired
    private ApplicationContext context;


    /**
     * @description: 监听单播 （采用自定义通道）
     * @param message   消息体
     * @param map  header头信息
     * @return
     * @description: 监听单播 （采用自定义通道）
     */
    @StreamListener(value = DefaultStream.DEFAULT_TN)
    public void handleAim(@Payload String message, @Headers Map<String, Object> map) {
        log.info("消息接收到" + message + "通道是:" + DefaultStream.DEFAULT_TN);
        dealMessage(message, map);
    }


    /**
     * @description: 监听广播 （采用自定义通道）
     * @param message   消息体
     * @param map  header头信息
     * @return
     * @description: 监听广播 （采用自定义通道）
     */
    @StreamListener(value = DefaultStream.DEFAULT_IN_BROADCAST)
    public void handleBroadcast(@Payload String message, @Headers Map<String, Object> map) {
        log.info("消息接收到" + message + "通道是:" + DefaultStream.DEFAULT_IN_BROADCAST);
        dealMessage(message, map);
    }


    /**
     * @description: 消息处理
     * @param message   消息体
     * @param map  header头信息
     * @return
     * @description: 消息处理
     */
    private void dealMessage(String message, Map<String, Object> map) {
        if (log.isDebugEnabled()) {
            log.debug("接收到消息 body:{}\nheaders:{}", message, JSON.toJSON(map));
        }
        if (map.containsKey(DefaultStream.HEADER_NAME)) {
            context.publishEvent(new InnerProtocolMessageEvent(JSON.parseObject(message, InnerProtocol.class), map));
            return;
        }
        context.publishEvent(new NormalProtocolMessageEvent(message, map));
    }


}
